package com.atkxp.sys.controller;

import com.alibaba.excel.EasyExcel;
import com.atkxp.sys.annotation.Log;
import com.atkxp.sys.entity.LoginLog;
import com.atkxp.sys.entity.Result;
import com.atkxp.sys.entity.User;
import com.atkxp.sys.enums.BusinessType;
import com.atkxp.sys.service.ILoginLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 系统访问记录 前端控制器
 * </p>
 *
 * @author kxp
 * @since 2023-10-09
 */
@RestController
@RequestMapping("/loginLog")
public class LoginLogController {
    @Autowired
    private ILoginLogService loginLogService;


    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:log:login')")
    public Result<Map<String, Object>> list(@RequestParam(value = "userName", required = false) String userName,
                                            @RequestParam(value = "ipaddr", required = false) String ipaddr,
                                            @RequestParam(value = "pageNo") Long pageNo,
                                            @RequestParam(value = "pageSize") Long pageSize) {

        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(userName), LoginLog::getUserName, userName);
        wrapper.like(StringUtils.hasLength(ipaddr), LoginLog::getIpaddr, ipaddr);
        wrapper.orderByDesc(LoginLog::getLoginTime);
        Page<LoginLog> page = new Page<>(pageNo, pageSize);
        loginLogService.page(page, wrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @PreAuthorize("hasAuthority('sys:log:login')")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{infoIds}")
    public Result remove(@PathVariable Long[] infoIds)
    {
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(LoginLog::getInfoId, infoIds);
        loginLogService.remove(wrapper);
        return Result.success("删除成功！");
    }

    @PreAuthorize("hasAuthority('sys:log:login')")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public Result clean()
    {
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        ArrayList<String> status = new ArrayList<>();
        status.add("1");
        status.add("0");
        wrapper.in(LoginLog::getStatus, status);
        loginLogService.remove(wrapper);
        return Result.success("清除成功！");
    }

    @PreAuthorize("hasAuthority('sys:log:login')")
    @Log(title = "登录日志", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(@RequestParam(value = "userName", required = false) String userName,
                         @RequestParam(value = "ipaddr", required = false) String ipaddr,
                         @RequestParam(value = "pageNo") Long pageNo,
                         @RequestParam(value = "pageSize") Long pageSize,
                         HttpServletResponse response) {

        response.setCharacterEncoding("utf-8");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        String fileName = "login_log_" + date;
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        LambdaQueryWrapper<LoginLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(userName), LoginLog::getUserName, userName);
        wrapper.like(StringUtils.hasLength(ipaddr), LoginLog::getIpaddr, ipaddr);
        wrapper.orderByDesc(LoginLog::getLoginTime);
        Page<LoginLog> page = new Page<>(pageNo, pageSize);
        loginLogService.page(page, wrapper);
        List<LoginLog> records = page.getRecords();

        try {
            EasyExcel.write(response.getOutputStream(), LoginLog.class).sheet("登录日志").doWrite(records);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
